package org.bing.engine.common.graniteds;

import java.io.InputStream;

import javax.servlet.ServletContext;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.granite.config.GraniteConfig;


public class GraniteConfigBuilder {
    private static final Log logger = LogFactory.getLog(GraniteConfigBuilder.class);

    public static GraniteConfig build(ServletContext context, String config) {
        logger.info("Use " + config + " init granite config.");
        try {
            GraniteConfig cfg = context != null ? (GraniteConfig) context.getAttribute(GraniteConfig.class.getName() + "_CACHE") : null;
            if (cfg != null) {
                logger.info("GraniteConfig is already exist, return it! ");
                return cfg;
            } else {
                return doBuild(context, config);
            }
        } catch (Exception e) {
            logger.error("Fail to build GraniteConfig, return null!", e);
            return null;
        }
    }

    private static GraniteConfig doBuild(ServletContext context, String res) throws Exception {
        InputStream ins = GraniteConfigBuilder.class.getResourceAsStream(res);
        GraniteConfig config = new GraniteConfig(null, ins, null, null);

        return config;
    }

    public static void main(String[] args) {
        GraniteConfig config = GraniteConfigBuilder.build(null, "/META-INF/bing-console-granite-config.xml");
        System.out.println(config);
    }
}
